<template>
  <div class="conversation-list">
    <div
      class="item border-gray-300 border-t cursor-pointer p-2"
      :class="{
        'bg-gray-100 hover:bg-gray-300': selectedId === item.id,
        'bg-white hover:bg-gray-200': selectedId !== item.id,
      }"
      v-for="item in items"
      :key="item.id"
      @contextmenu.prevent="showContextMenu(item.id)"
    >
      <a @click.prevent="goToConversation(item.id)">
        <div
          class="flex justify-between items-center text-sm leading-5 text-gray-500"
        >
          <span>{{ item.selectedModel }}</span>
          <span>{{ item.updatedAt }}</span>
        </div>
        <h2 class="font-semibold leading-6 text-gray-900 truncate">
          {{ item.title }}
        </h2>
      </a>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import { ConversationProps } from "../types";
import { useConversationStore } from '../stores/conversation'


const store = useConversationStore()

defineProps<{ items: ConversationProps[] }>();
const router = useRouter();

const selectedId = ref(0);

const goToConversation = (id: number) => {
  router.push({ path: `/conversation/${id}` });
  selectedId.value = id;
};

const showContextMenu = (id: number) => {
  window.electronAPI.showContextMenu(id);
};

onMounted(() => {
  window.electronAPI.onDeleteConversation(async (id: number) => {
    await store.deleteConversation(id);
    if (store.selectedId === id) {
      store.selectedId = -1;
      router.push("/");
    }
  });
});
</script>
